package com.netty.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Set;

public class TimeClientHandle implements Runnable{
    private String host;
    private int port;
    private Selector selector;
    private SocketChannel socketChannel;
    private volatile boolean stop;

    /**
     * 初始化多路复用器和SocketChannel对象
     */
    public TimeClientHandle(String host, int port) {
        this.host = host==null?"127.0.0.1":host;
        this.port = port;
        try {
            //1.打开SocketChannel
            socketChannel = SocketChannel.open();
            //2.设置非阻塞模式
            socketChannel.configureBlocking(false);
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    @Override
    public void run() {
        try {
            //6.创建Selector,启动线程
            selector = Selector.open();
            doConnect();
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }
        //7.轮询多路复用器Selector,有就绪的channel，执行handleInput方法
        while (!stop){
            try {
                SelectionKey key;
                selector.select(1000);
                Set<SelectionKey> selectKeys = selector.selectedKeys();
                Iterator<SelectionKey> it = selectKeys.iterator();
                while (it.hasNext()){
                    key = it.next();
                    it.remove();
                    try {
                        handleInput(key);
                    } catch (IOException e) {
                        e.printStackTrace();
                        key.cancel();
                        if(key.channel() !=null){
                            key.channel().close();
                        }
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void doConnect() throws IOException {
        //3.异步连接服务端，
        //4.判断连接结果，如果直接连接成功，则注册到多路复用器上，发送请求消息，读应答，连接不成功，向Reactor多路复用器注册op_connect事件
        if(socketChannel.connect(new InetSocketAddress(host,port))){
            socketChannel.register(selector, SelectionKey.OP_READ);
            doWrite(socketChannel);
        }else {
            //5.向Reactor多路复用器注册op_connect事件
            socketChannel.register(selector,SelectionKey.OP_CONNECT);
        }
    }

    private void doWrite(SocketChannel sc) throws IOException {
        for (int i = 0; i < 10; i++) {
            //12.decode消息
            byte[] req = ("客户端发送的消息index="+i).getBytes();
            ByteBuffer writeBuffer = ByteBuffer.allocate(req.length);
            writeBuffer.put(req);
            writeBuffer.flip();
            //13.异步写ByteBuffer到SoceketChannel
            sc.write(writeBuffer);
            //缓冲区消息是否全部发送完成
            if (!writeBuffer.hasRemaining()){
                System.out.println("Send order 2 server success");
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private void handleInput(SelectionKey key) throws IOException {
        //判断是否连接成功
        if(key.isValid()){
            SocketChannel sc = (SocketChannel)key.channel();
            //8.处理连接事件
            if (key.isConnectable()){
                //9.判断连接是否完成，等到客户端连接成功
                if (sc.finishConnect()){
                    //10.注册读事件到多路复用器
                    sc.register(selector,SelectionKey.OP_READ);
                    doWrite(sc);
                }else {
                    System.exit(1);
                }
            }
            //客户端收到服务端的应答消息
            if(key.isReadable()){
                ByteBuffer readBuffer = ByteBuffer.allocate(1024);
                //11.异步读消息到缓冲区
                int readBytes = sc.read(readBuffer);
                if(readBytes >0){
                    readBuffer.flip();
                    byte[] bytes = new byte[readBuffer.remaining()];
                    readBuffer.get(bytes);
                    String body = new String(bytes, StandardCharsets.UTF_8);
                    System.out.println("now is :"+body);
                    //读到消息之后退出线程循环
//                    this.stop = true;
                }else if(readBytes<0) {
                    key.cancel();
                    sc.close();
                }
            }
        }
    }
}
